package com.sky.handler;

import com.alibaba.fastjson.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;
import java.util.HashMap;

/**
 * @projectName: netty-cloud
 * @package: com.sky.handler
 * @className: MyAuthenticationEntryPoint
 * @author: zhl
 * @description: 请求未认证处理
 * @date: 2024/4/25 15:10
 * @version: 1.0
 */
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    /**
     * Commences an authentication scheme.
     * <p>
     * <code>ExceptionTranslationFilter</code> will populate the <code>HttpSession</code>
     * attribute named
     * <code>AbstractAuthenticationProcessingFilter.SPRING_SECURITY_SAVED_REQUEST_KEY</code>
     * with the requested target URL before calling this method.
     * <p>
     * Implementations should modify the headers on the <code>ServletResponse</code> as
     * necessary to commence the authentication process.
     *
     * @param request       that resulted in an <code>AuthenticationException</code>
     * @param response      so that the user agent can begin authentication
     * @param authException that caused the invocation
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        String requestURI = request.getRequestURI();
        System.out.println("请求路径" + requestURI);
        HashMap<String,Object> hashMap = new HashMap<>(16);
        hashMap.put("code",400);
        hashMap.put("msg","当前用户未登录，请先登录");
        hashMap.put("data",authException.getMessage());
        hashMap.put("requestURI",requestURI);
        String json = JSON.toJSONString(hashMap);

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
